<template>
  <div class="fire-detection-container">
    <div class="page-header">
      <h1 class="page-title">火灾检测系统</h1>
      <p class="page-description">基于AI视觉算法的智能火灾检测与预警系统</p>
    </div>

    <div class="main-content">
      <div class="content-layout">
        <!-- 左侧：图片上传区域 -->
        <div class="upload-section">
          <div class="upload-card">
            <div class="upload-header">
              <h3>图片上传</h3>
              <p>支持 JPG、PNG、JPEG 格式，最大 10MB</p>
            </div>
            
            <div class="upload-area" 
                 :class="{ 'drag-over': isDragOver }"
                 @drop="handleDrop"
                 @dragover="handleDragOver"
                 @dragleave="handleDragLeave"
                 @click="triggerFileInput">
              <div v-if="!selectedImage" class="upload-placeholder">
                <div class="upload-icon">
                  <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M21 19V5C21 3.9 20.1 3 19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19ZM8.5 13.5L11 16.51L14.5 12L19 18H5L8.5 13.5Z" fill="#4facfe"/>
                  </svg>
                </div>
                <p class="upload-text">点击或拖拽图片到此处</p>
                <p class="upload-hint">支持 JPG、PNG、JPEG 格式</p>
              </div>
              
              <div v-else class="image-preview">
                <img :src="selectedImage" alt="预览图片" class="preview-image">
                <div class="image-overlay">
                  <button class="change-btn" @click.stop="triggerFileInput">更换图片</button>
                  <button class="remove-btn" @click.stop="removeImage">删除</button>
                </div>
              </div>
            </div>
            
            <input 
              ref="fileInput"
              type="file" 
              accept="image/*" 
              @change="handleFileSelect"
              style="display: none">
            
            <div class="upload-actions">
              <button 
                class="detect-btn" 
                :disabled="!selectedImage || isDetecting"
                @click="startDetection">
                <svg v-if="!isDetecting" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M12 2L13.09 8.26L22 9L13.09 9.74L12 16L10.91 9.74L2 9L10.91 8.26L12 2Z" fill="currentColor"/>
                </svg>
                <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="spinning">
                  <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="currentColor"/>
                </svg>
                {{ isDetecting ? '检测中...' : '开始检测' }}
              </button>
            </div>
          </div>
        </div>

        <!-- 右侧：检测结果区域 -->
        <div class="result-section" v-if="detectionResult">
          <div class="result-card">
            <div class="result-header">
              <h3>检测结果</h3>
              <div class="result-status" :class="detectionResult.hasFire ? 'fire-detected' : 'no-fire'">
                <span class="status-icon">
                  {{ detectionResult.hasFire ? '🔥' : '✅' }}
                </span>
                <span class="status-text">
                  {{ detectionResult.hasFire ? '检测到火灾' : '未检测到火灾' }}
                </span>
                <button 
                  v-if="detectionResult.hasFire" 
                  class="stop-alarm-btn" 
                  @click="stopAlarmSound"
                  title="停止报警">
                  🔇
                </button>
              </div>
            </div>
            
          <div class="result-details">
            <div class="confidence-score">
              <span class="label">置信度：</span>
              <span class="score" :class="getConfidenceClass(detectionResult.confidence)">
                {{ (detectionResult.confidence * 100).toFixed(1) }}%
              </span>
            </div>
            
            <div class="detection-time">
              <span class="label">检测时间：</span>
              <span class="time">{{ detectionResult.timestamp }}</span>
            </div>
          </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 音频元素 -->
    <audio ref="audioRef" preload="auto">
      <source src="/split.flac" type="audio/flac">
      您的浏览器不支持音频播放。
    </audio>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 响应式数据
const selectedImage = ref(null)
const isDragOver = ref(false)
const fileInput = ref(null)
const detectionResult = ref(null)
const isDetecting = ref(false)
const audioRef = ref(null)

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    processFile(file)
  }
}

// 处理拖拽上传
const handleDrop = (event) => {
  event.preventDefault()
  isDragOver.value = false
  
  const files = event.dataTransfer.files
  if (files.length > 0) {
    processFile(files[0])
  }
}

const handleDragOver = (event) => {
  event.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = (event) => {
  event.preventDefault()
  isDragOver.value = false
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click()
}

// 处理文件
const processFile = (file) => {
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件')
    return
  }
  
  // 检查文件大小 (10MB)
  if (file.size > 10 * 1024 * 1024) {
    alert('文件大小不能超过10MB')
    return
  }
  
  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    selectedImage.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 删除图片
const removeImage = () => {
  selectedImage.value = null
  detectionResult.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 开始检测
const startDetection = async () => {
  if (!selectedImage.value) return
  
  try {
    // 设置检测状态
    isDetecting.value = true
    detectionResult.value = null
    
    // 将base64图片发送到火灾检测服务API
    const response = await fetch('http://localhost:5001/api/fire-detection/detect-base64', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        image: selectedImage.value
      }),
      mode: 'cors' // 明确指定CORS模式
    })
    
    const result = await response.json()
    
    if (result.success) {
      detectionResult.value = {
        hasFire: result.has_fire,
        confidence: result.confidence,
        timestamp: new Date().toLocaleString('zh-CN')
      }
      
      // 如果检测到火灾，播放报警音频
      if (result.has_fire) {
        playAlarmSound()
      }
    } else {
      // 显示错误信息
      alert(`检测失败: ${result.message}`)
    }
  } catch (error) {
    console.error('检测过程中发生错误:', error)
    alert(`检测过程中发生错误: ${error.message}`)
  } finally {
    // 重置检测状态
    isDetecting.value = false
  }
}

// 播放报警音频
const playAlarmSound = () => {
  try {
    if (audioRef.value) {
      // 重置音频到开始位置
      audioRef.value.currentTime = 0
      // 播放音频
      audioRef.value.play().catch(error => {
        console.warn('音频播放失败:', error)
        // 如果自动播放被阻止，可以显示提示
        console.log('请点击页面以启用音频播放')
      })
    }
  } catch (error) {
    console.error('播放报警音频时出错:', error)
  }
}

// 停止报警音频
const stopAlarmSound = () => {
  try {
    if (audioRef.value) {
      audioRef.value.pause()
      audioRef.value.currentTime = 0
    }
  } catch (error) {
    console.error('停止报警音频时出错:', error)
  }
}

// 获取置信度样式类
const getConfidenceClass = (confidence) => {
  if (confidence >= 0.9) return 'high'
  if (confidence >= 0.7) return 'medium'
  return 'low'
}
</script>

<style scoped>
.fire-detection-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  color: white;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 10px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

.page-description {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.content-layout {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.upload-section {
  flex: 1;
  min-width: 0;
}

.upload-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  width: 100%;
  height: fit-content;
}

.upload-header {
  text-align: center;
  margin-bottom: 30px;
}

.upload-header h3 {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 8px;
}

.upload-header p {
  color: #666;
  margin: 0;
}

.upload-area {
  border: 2px dashed #4facfe;
  border-radius: 15px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8fbff;
  position: relative;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area:hover,
.upload-area.drag-over {
  border-color: #00f2fe;
  background: #e3f2fd;
  transform: translateY(-2px);
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.upload-icon {
  opacity: 0.6;
}

.upload-text {
  font-size: 1.2rem;
  color: #333;
  margin: 0;
  font-weight: 500;
}

.upload-hint {
  color: #666;
  margin: 0;
  font-size: 0.9rem;
}

.image-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  border-radius: 10px;
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.image-overlay {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 10px;
}

.change-btn,
.remove-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 0.9rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.change-btn {
  background: #4facfe;
  color: white;
}

.change-btn:hover {
  background: #00f2fe;
  transform: translateY(-1px);
}

.remove-btn {
  background: #ff6b6b;
  color: white;
}

.remove-btn:hover {
  background: #ff5252;
  transform: translateY(-1px);
}

.upload-actions {
  margin-top: 20px;
  text-align: center;
}

.detect-btn {
  background: linear-gradient(45deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  padding: 15px 30px;
  border-radius: 25px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 10px;
  transition: all 0.3s ease;
  box-shadow: 0 5px 15px rgba(79, 172, 254, 0.3);
}

.detect-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(79, 172, 254, 0.4);
}

.detect-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.result-section {
  flex: 1;
  min-width: 0;
}

.result-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  width: 100%;
  height: fit-content;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.result-header h3 {
  margin: 0;
  color: #333;
}

.result-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: 600;
}

.result-status.fire-detected {
  background: #ffebee;
  color: #d32f2f;
}

.result-status.no-fire {
  background: #e8f5e8;
  color: #2e7d32;
}

.status-icon {
  font-size: 1.2rem;
}

.stop-alarm-btn {
  background: #ff6b6b;
  border: none;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  margin-left: 10px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.stop-alarm-btn:hover {
  background: #ff5252;
  transform: scale(1.1);
  box-shadow: 0 4px 8px rgba(0,0,0,0.3);
}

.result-details {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.confidence-score,
.detection-time {
  flex: 1;
}

.label {
  font-weight: 500;
  color: #666;
}

.score {
  font-weight: 600;
  font-size: 1.1rem;
}

.score.high {
  color: #2e7d32;
}

.score.medium {
  color: #f57c00;
}

.score.low {
  color: #d32f2f;
}

.time {
  color: #333;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .fire-detection-container {
    padding: 15px;
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .content-layout {
    flex-direction: column;
    gap: 20px;
  }
  
  .upload-card,
  .result-card {
    padding: 20px;
  }
  
  .result-details {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
